import React from "react"
import { useNavigate } from "react-router"
import { LockOutlined, UserOutlined } from "@ant-design/icons"
import { Button, Form, Input, message } from "antd"
import { userLogin } from "@/api/auth"
import logo from "@/assets/images/dog.svg"
import { TOKEN } from "@/constants"
import "./index.scss"
import type { FormProps } from "antd"

/**
 * 登录页
 */
const LoginPage: React.FC = () => {
  const navigate = useNavigate()

  /**
   * 登录
   */
  const onFinish: FormProps<UserLoginRequest>["onFinish"] = async (values) => {
    try {
      const res = await userLogin(values)
      if (res.data) {
        // 保存 token 至缓存中
        localStorage.setItem(TOKEN, res.data.token)
        message.success("登录成功")
        navigate("/", { replace: true })
      }
    } catch (e: any) {
      message.error("登录失败，" + e.message)
    }
  }

  return (
    <div className="login-page">
      <div className="login-page__header">
        <img className="login-page__logo" src={logo} alt="logo" />
        <span className="login-page__title">XYZ</span>
      </div>
      <div className="login-page__subtitle">
        <span>Agentic AI</span>
      </div>
      <div className="login-page__form">
        <Form name="login" onFinish={onFinish}>
          <Form.Item<UserLoginRequest> name="userName" rules={[{ required: true, message: "请输入用户名" }]}>
            <Input size="large" prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item<UserLoginRequest> name="password" rules={[{ required: true, message: "请输入密码" }]}>
            <Input.Password size="large" prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button size="large" block type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default LoginPage
